﻿using DG.Tweening;
using UnityEngine;
using UnityEngine.Events;
#if UNITY_EDITOR
using UnityEditor;
#endif

public abstract class UIAnimation:MonoBehaviour
{
    [FieldLabel("播放完成后是否删除动画")]
    public bool isKill;

    [FieldLabel("循环次数")]
    [Tooltip("-1无限循环")]
    public int loop;

    [FieldLabel("动画持续时间")]
    public float duration;

    [FieldLabel("循环方式")]
    public LoopType loopType;

    [FieldLabel("动画缓动类型")]
    public Ease ease = Ease.Linear;

    [FieldLabel("动画开始时间")]
    public StartAnimation startAnimation;

   
    public UnityEvent onComplete;

    protected Tweener tweener;

    protected abstract Tweener GetTweener(RectTransform rectTransform);

    protected virtual void Awake()
    {
        tweener = GetTweener(transform as RectTransform);
        tweener.SetLoops(loop, loopType);
        tweener.SetEase(ease);
        tweener.Pause();
        tweener.OnComplete(OnComplete);

        if(startAnimation == StartAnimation.初始化)
        {
            tweener.Play();
        }
    }

    protected virtual void OnEnable()
    {
        if(startAnimation == StartAnimation.显示)
            tweener.Play();
    }

    public virtual void Hide()
    {
        if (startAnimation == StartAnimation.关闭)
            tweener.Play();
    }

    protected void OnComplete()
    {
        if(onComplete!=null)
        {
            onComplete.Invoke();
        }
        if (isKill)
        {
            tweener.Kill();
            DestroyImmediate(this, true);
        }
    }

#if UNITY_EDITOR
    protected virtual void OnDrawGizmos()
    {
        if (GetComponent<RectTransform>()==null)
        {
            EditorUtility.DisplayDialog("错误", "没有UI组件", "确定");
            DestroyImmediate(this, true);
        }
    }
#endif
}
